// AIQuestionPage.tsx
import React, { useState, useEffect } from 'react';

const LANGUAGES = ['go语言', 'js语言'];
const TYPES = [
  { label: '单选题', value: '单选题' },
  { label: '多选题', value: '多选题' },
  { label: '编程题', value: '编程题' },
];

interface Props {
  onBack: () => void;
  onAdd: (selected: any[]) => void;
}

const AIQuestionPage: React.FC<Props> = ({ onBack, onAdd }) => {
  const [type, setType] = useState(() => localStorage.getItem('aiType') || '单选题');
  const [lang, setLang] = useState(() => localStorage.getItem('aiLang') || LANGUAGES[0]);
  const [count, setCount] = useState<string>(() => localStorage.getItem('aiCount') || '1');
  const [countError, setCountError] = useState('');
  const [loading, setLoading] = useState(false);
  const [questions, setQuestions] = useState<any[]>([]);
  const [selected, setSelected] = useState<number[]>([]);

  // 从 localStorage 恢复状态
  useEffect(() => {
    const storedType = localStorage.getItem('aiType');
    const storedLang = localStorage.getItem('aiLang');
    const storedCount = localStorage.getItem('aiCount');

    if (storedType) setType(storedType);
    if (storedLang) setLang(storedLang);
    if (storedCount) {
      setCount(storedCount);
      // 验证数量
      const num = Number(storedCount);
      if (num < 1 || num > 10) {
        setCountError('题目数量需在1-10之间');
      }
    }
  }, []);

  const handleCountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    // 允许空字符串
    if (val === '' || (/^\d+$/.test(val) && val.length <= 2)) {
      setCount(val);
      localStorage.setItem('aiCount', val);
      // 校验
      if (val === '') {
        setCountError('请输入题目数量');
      } else {
        const num = Number(val);
        if (num < 1 || num > 10) {
          setCountError('题目数量需在1-10之间');
        } else {
          setCountError('');
        }
      }
    }
  };

  const handleTypeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newType = e.target.value;
    setType(newType);
    localStorage.setItem('aiType', newType);
  };

  const handleLangChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newLang = e.target.value;
    setLang(newLang);
    localStorage.setItem('aiLang', newLang);
  };

  const handleGenerate = async () => {
    if (countError || !count) return;
    setLoading(true);
    setQuestions([]); // 清空上一次内容
    setSelected([]);
    const res = await fetch('/api/ai-generate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ type, lang, count: Number(count) }),
    });
    const data = await res.json();
    setQuestions(data);
    setLoading(false);
  };

  const handleSelect = (idx: number, checked: boolean) => {
    setSelected(checked ? [...selected, idx] : selected.filter(i => i !== idx));
  };

  const handleAdd = () => {
    onAdd(selected.map(i => questions[i]));
    setQuestions([]);
    setSelected([]);
  };

  return (
    <div style={{ display: 'flex', minHeight: 500 }}>
      {/* 左侧区域 */}
      <div style={{ width: '30%', borderRight: '1px dashed #ccc', padding: 32 }}>
        <h2 style={{ fontSize: 18, marginBottom: 16 }}>AI生成试题</h2>
        <div style={{ marginBottom: 12 }}>
          <label>题型：</label>
          <select value={type} onChange={handleTypeChange}
            style={{ width: 120, height: 30, border: '1px solid #ccc', borderRadius: 4, padding: '0 8px' }}>
            {TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
          </select>
        </div>
        <div style={{ marginBottom: 12 }}>
          <label>题目数量：</label>
          <input type="number" min={1} max={10} value={count} onChange={handleCountChange}
            style={{ width: 60, height: 30, border: '1px solid #ccc', borderRadius: 4, padding: '0 8px' }} />
          <span style={{ color: '#faad14', marginLeft: 8 }}>最小1，最大10</span>
          {countError && <div style={{ color: 'red', fontSize: 13, marginTop: 2 }}>{countError}</div>}
        </div>
        <div style={{ marginBottom: 24 }}>
          <label>语言：</label>
          <select value={lang} onChange={handleLangChange}
            style={{ width: 120, height: 30, border: '1px solid #ccc', borderRadius: 4, padding: '0 8px' }}>
            {LANGUAGES.map(l => <option key={l} value={l}>{l}</option>)}
          </select>
        </div>
        <button
          onClick={handleGenerate}
          disabled={!!countError || !count || loading}
          style={{ background: '#1677ff', color: '#fff', border: 'none', borderRadius: 4, padding: '8px 24px', fontSize: 16, opacity: (!!countError || !count || loading) ? 0.5 : 1, cursor: (!!countError || !count || loading) ? 'not-allowed' : 'pointer' }}
        >生成并预览题库</button>
        <div style={{ marginTop: 16 }}>
          <button onClick={onBack} style={{ color: '#1677ff', background: 'none', border: 'none', fontSize: 16 }}>← 返回题库管理</button>
        </div>
      </div>
      {/* 右侧区域 */}
      <div style={{ width: '70%', padding: 32, minHeight: 500 }}>
        <div style={{ color: '#eee', fontSize: 32, textAlign: 'center', marginTop: 80, display: questions.length ? 'none' : 'block' }}>
          AI生成区域
        </div>
        {loading && <div style={{ textAlign: 'center', marginTop: 80 }}>AI生成中...</div>}
        {questions.length > 0 && !loading && (
          <div>
            <h3 style={{ fontSize: 16, marginBottom: 8 }}>预览题库（可多选添加）</h3>
            <ul style={{ maxHeight: 'none', overflow: 'auto', padding: 0 }}>
              {questions.map((q, idx) => (
                <li key={idx} style={{ borderBottom: '1px solid #eee', padding: 8, display: 'flex', alignItems: 'center' }}>
                  <input type="checkbox" checked={selected.includes(idx)} onChange={e => handleSelect(idx, e.target.checked)} style={{ marginRight: 8 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ color: '#1677ff', fontWeight: 500 }}>{q.title}</div>
                    <div style={{ fontSize: 13, color: '#888' }}>{q.content}</div>
                    {q.options && Array.isArray(q.options) && q.options.length > 0 && (
                      <div style={{ fontSize: 13, color: '#555' }}>选项：{q.options.join('、')}</div>
                    )}
                    {/* 只在非编程题时显示答案 */}
                    {q.answer && type !== '编程题' && (
                      <div style={{ fontSize: 13, color: '#d46b08', marginTop: 4 }}>答案：{q.answer}</div>
                    )}
                  </div>
                </li>
              ))}
            </ul>
            <div style={{ marginTop: 16, textAlign: 'right' }}>
              <button onClick={() => {
                setQuestions([]);
                setSelected([]);
              }} style={{ marginRight: 8 }}>取消</button>
              <button onClick={handleAdd} disabled={selected.length === 0} style={{ background: '#1677ff', color: '#fff', border: 'none', borderRadius: 4, padding: '6px 24px' }}>添加到题库</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default AIQuestionPage;